<template>
  <div class="property-form">
    <el-collapse v-model="activeIndex" accordion>
      <el-collapse-item v-for="(condition, index) in props.node.conditions" :key="condition.id" :name="index"
        :class="{ 'active-condition': activeIndex === index }">
        <template #title>
          <span class="condition-title">
            {{ condition.name || '未命名条件' }}
            <el-tag v-if="!condition.multiplicable" type="info">唯一</el-tag>
          </span>
        </template>

        <div class="condition-content">
          <el-form :model="condition" :rules="rules">
            <!-- 类型选择 -->
            <el-form-item label="条件类型" prop="type">
              <el-select v-model="condition.type" :disabled="!condition.multiplicable && conditions.length > 1"
                @change="updateConditionName(index)">
                <el-option v-for="opt in availableTypes" :key="opt.type" :label="opt.label" :value="opt.type"
                  :disabled="opt.disabled" />
              </el-select>
            </el-form-item>

            <!-- 名称输入 -->
            <el-form-item v-if="condition.type === 'custom'" label="条件名称" prop="name">
              <el-input v-model="condition.name" placeholder="输入自定义名称" :disabled="!condition.multiplicable" />
            </el-form-item>
          </el-form>

          <div class="condition-actions">
            <el-button v-if="index > 0" type="danger" @click.stop="removeCondition(index)"
              :disabled="!condition.multiplicable">
              删除
            </el-button>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>

    <el-button class="add-button" type="primary" @click="addCondition" icon="Plus">
      添加条件
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { computed, markRaw } from 'vue'

const props = defineProps({
  node: Node
})

console.log("branch:", JSON.stringify(markRaw(props.node.data.conditions)))

// 条件类型配置
const CONDITION_TYPES = [
  { type: 'default', label: '默认条件', multiplicable: false },
  { type: 'time', label: '时间条件', multiplicable: false },
  { type: 'custom', label: '自定义条件', multiplicable: true }
];

// 动态计算可用类型
const availableTypes = computed(() => {
  const usedTypes = new Set(props.node.data.conditions.value.map(c => c.type));
  return CONDITION_TYPES.map(opt => ({
    ...opt,
    disabled: !opt.multiplicable && usedTypes.has(opt.type)
  }));
});

// 添加新条件
const addCondition = () => {
  props.node.data.conditions.value.push({
    id: crypto.randomUUID(),
    type: 'custom',
    name: '新自定义条件',
    multiplicable: true
  });
  activeIndex.value = conditions.value.length - 1;
};

// 删除条件
const removeCondition = (index: number) => {
  if (conditions.value[index].multiplicable) {
    conditions.value.splice(index, 1);
    activeIndex.value = Math.max(0, index - 1);
  }
};
</script>

<style scoped>
.property-form {
  width: 100%;
  padding: 10px;
}
</style>